import { h } from 'preact';
import { useState, useEffect } from 'preact/hooks';
import { add, destory, envoke } from "@store";
import { getData } from "@store/data";
import RectDND from "@comps/dnd";
import "@static:css/components/chart/index.less";

import { loadScript } from "./import";

export default (props) => {
    const { uuid, pid } = props;
    const { width, height, left, top } = getData(uuid, 'rect');
    const [style, setStyle] = useState({ width, height, left, top });
    useEffect(() => {

        loadScript('https://cdn.bootcdn.net/ajax/libs/echarts/5.0.0-rc.1/echarts.min.js').then(d => {
            const { code } = d;
            if(code === 200){
                const myChart = echarts.init(document.getElementById(uuid));
                
                const updateOption = () => {
                    const option = getData(uuid, 'chart');
                    console.log('option => ', option);
                    myChart.setOption(option);
                }

                updateOption();

                add(uuid, 'setOption', () => {
                    myChart.clear();//fixed:有些时候，图表中有时候坐标系不刷新或者图表不刷新，有可能是图表绘制怪异问题
                    updateOption();
                })
                add(uuid, 'resize', opts => {
                    myChart.resize(opts);
                })
                add(uuid, 'setStyle', opts => {
                    setStyle(opts);
                })
            }
        })

        return () => {
            destory(uuid)
        }

    }, []);

    useEffect(() => {
        const { width, height, left, top } = style;
        envoke(uuid, 'resize', {
            width, 
            height, 
            left, 
            top
        })
    }, [style]);

    return <RectDND id={`parent-${uuid}`} uuid={uuid} onDragStart={() => {
                envoke('config', 'updateRectId', uuid);
            }} onResize={(width, height) => {
                setStyle({
                    width, height
                });
            }}>
                <div id={uuid} className="c-chart-container" style={style}></div>
        </RectDND>
}